/*
 * Copyright 2021-2030 itbox.cn All right reserved. This software is the confidential and proprietary information
 * of itbox.cn ("Confidential Information"). You shall not disclose such Confidential Information and shall use it
 * only in accordance with the terms of the license agreement you entered into with itbox.cn.
 */
package cn.itbox.example.application.service.impl;

import cn.itbox.example.application.facotry.UserFactory;
import cn.itbox.example.application.service.UserCommandService;
import cn.itbox.uap.domain.event.publish.DomainEventPublisher;
import cn.itbox.example.domain.event.user.UserCreateEvent;
import cn.itbox.example.domain.event.user.UserDeleteEvent;
import cn.itbox.example.domain.event.user.UserUpdateEvent;
import cn.itbox.example.domain.repository.UserRepository;
import cn.itbox.example.model.request.CreateUserRequest;
import cn.itbox.example.model.request.UpdateUserRequest;
import cn.itbox.example.domain.model.UserModel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @BelongProject springboot-study
 * @BelongPackage cn.itbox.example.application.service.impl
 * @Description TODO
 * @ClassName UserCommandServiceImpl
 * @Author xingc
 * @Date 2023/11/26 23:14
 * @Version 1.0.0
 */
@Slf4j
@Service
public class UserCommandServiceImpl implements UserCommandService {
    @Resource
    private UserRepository userRepository;

    @Autowired
    private DomainEventPublisher domainEventPublisher;

    @Override
    public Long create(CreateUserRequest request) {
        // 创建用户
        UserModel model = UserFactory.createUser(request);
        model.bindAddress(request.getProvince(), request.getCity(), request.getCounty());
        model.bindRoleByRoleId(request.getRoles());

        // 保存用户
        //UserModel savedModel = model.save();
        userRepository.save(model);

        // 发布事件
        domainEventPublisher.publishEvent(new UserCreateEvent(model));
        return  model.getId();
    }

    @Override
    public void update(UpdateUserRequest request) {
        // 创建用户
        UserModel model = UserFactory.updateUser(request);
        model.bindAddress(request.getProvince(), request.getCity(), request.getCounty());
        model.bindRoleByRoleId(request.getRoles());

        // 保存用户
        //UserModel savedModel = model.save();
        userRepository.save(model);

        // 发布事件
        domainEventPublisher.publishEvent(new UserUpdateEvent(model));
    }

    @Override
    public void delete(Long id) {
        // 创建用户
        UserModel model = UserFactory.byId(id);

        // 删除用户
        //model.delete();
        userRepository.delete(id);

        // 发布事件
        domainEventPublisher.publishEvent(new UserDeleteEvent(id));
    }
}
